<template>
  <base-breadcrumb>
    <div class="about-master-container" v-loading="spinning">
      <a-card>
        <title-name :title="disabled? '信息详情' : '基本信息'" />
        <a-form-model ref="form" :model="formInfo" :rules="rules">
          <a-row>
            <template v-if="!formInfo.id">
              <template v-if="formInfo.safeDeptType === 'CO'">
                <a-col span="16">
                  <a-form-model-item label="所属单位">
                    <BaseInput disabled placeholder="请选择" value="总部机关安监部" />
                  </a-form-model-item>
                </a-col>
<!--                <a-col span="8">-->
<!--                  <a-form-model-item label="所属项目">-->
<!--                    <BaseInput disabled />-->
<!--                  </a-form-model-item>-->
<!--                </a-col>-->
              </template>
              <template v-if="formInfo.safeDeptType === 'BC'">
                <a-col span="16">
                  <a-form-model-item label="所属单位">
<!--                    <SelectSubCompany disabled v-model="formInfo.branchComId" />-->
                    <org-tree-select v-model="formInfo.branchComId" disabled></org-tree-select>
                  </a-form-model-item>
                </a-col>
<!--                <a-col span="8">-->
<!--                  <a-form-model-item label="公司/分公司">-->
<!--                    <SelectSubCompany disabled v-model="formInfo.branchComId" />-->
<!--                  </a-form-model-item>-->
<!--                </a-col>-->
<!--                <a-col span="8">-->
<!--                  <a-form-model-item label="所属项目">-->
<!--                    <BaseInput disabled />-->
<!--                  </a-form-model-item>-->
<!--                </a-col>-->
              </template>
              <template v-if="formInfo.safeDeptType === 'PD'">
                                <a-col span="16">
                                  <a-form-model-item label="所属单位">
                                    <org-tree-select disabled v-model="formInfo.projectId"
                                                     is-auto-select-first
                                                     @getProjectInfo="getProjectInfo"
                                                     @select="selecOrg"/>
                                  </a-form-model-item>
                                </a-col>
<!--                <a-col span="8">-->
<!--                  <a-form-model-item label="分公司">-->
<!--                    <SelectSubCompany disabled v-model="formInfo.branchComId" />-->
<!--                  </a-form-model-item>-->
<!--                </a-col>-->
<!--                <a-col span="8">-->
<!--                  <a-form-model-item label="所属项目">-->
<!--                    <SelectProject-->
<!--                      v-model="formInfo.projectId"-->
<!--                      placeholder="请选择"-->
<!--                      disabled-->
<!--                      :isEdit="formInfo.id !== null"-->
<!--                      :form="formInfo"-->
<!--                      key-value="branchComId"-->
<!--                    />-->
<!--                  </a-form-model-item>-->
<!--                </a-col>-->
              </template>
            </template>
            <template v-else>
                <template v-if="formInfo.safeDeptType === 'CO'">
                    <a-col span="16">
                        <a-form-model-item label="所属单位">
                            <BaseInput disabled placeholder="请选择" value="总部机关安监部" />
                        </a-form-model-item>
                    </a-col>
                </template>
              <a-col span="16" v-else>
                <a-form-model-item label="所属单位" prop="projectId">
                  <org-tree-select
                          :disabled="disabled"
                          is-auto-select-first
                          is-need-auth
                          check-strictly
                          v-model="formInfo.projectId"
                          @getProjectInfo="getProjectInfo"
                          @select="selecOrg"
                  />
                </a-form-model-item>
              </a-col>
<!--              <a-col span="8">-->
<!--                <a-form-model-item label="公司/分公司" prop="branchComId">-->
<!--                  <BSelect v-model="formInfo.branchComId" :request="requestBranchCom" :disabled="disabled" />-->
<!--                </a-form-model-item>-->
<!--              </a-col>-->
<!--              <a-col span="8">-->
<!--                <a-form-model-item label="所属项目" prop="projectId">-->
<!--                  <SelectProject-->
<!--                    :disabled="disabled"-->
<!--                    allowClear-->
<!--                    @selectChange="onSelectChange"-->
<!--                    v-model="formInfo.projectId"-->
<!--                    placeholder="请选择"-->
<!--                    :isEdit="formInfo.id !== null"-->
<!--                    :autoSelected="false"-->
<!--                    :form="formInfo"-->
<!--                    key-value="branchComId"-->
<!--                  />-->
<!--                </a-form-model-item>-->
<!--              </a-col>-->
            </template>
            <a-col span="8">
              <a-form-model-item label="姓名" prop="userId">
                <ASelectOrgPeople
                  :disabled="disabled"
                  @onSelectChange="getPeople"
                  :init="false"
                  :form="formInfo"
                  key-value="orgId"
                  option-key="id"
                  v-model="formInfo.userId"
                ></ASelectOrgPeople>
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="员工编号">
                <BaseInput disabled placeholder="请选择" v-model="formInfo.jobNum" />
              </a-form-model-item>
            </a-col>
            <a-col span="8" class="history-data">
              <a-form-model-item label="安全岗位信息" prop="safetyPostId" >
                <div v-if="disabled" class="post">{{formInfo.post}}</div>
                <a-select v-else
                  :disabled="disabled"
                  v-model="formInfo.safetyPostId"
                  placeholder="请选择"
                  @change="handlePost">
                  <a-select-option
                    v-for="item in postList" :key="item.id"
                    :value="item.id">
                    {{item.post}}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="岗位">
                <BaseInput disabled placeholder="请选择" v-model="formInfo.postPNames &&　formInfo.postPNames.join('，')" />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="性别">
                <BaseInput disabled placeholder="请选择" v-model="formInfo.sex" />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="合同类型" prop="contractTypeId">
                <BSelect :disabled="disabled"
                         v-model="formInfo.contractTypeId"
                         :init="true"
                         :request="e => getSelectListByType({ type:25 })"
                />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="电话号码">
                <BaseInput disabled placeholder="请选择" v-model="formInfo.phone" />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="出生年月">
                <BaseInput disabled placeholder="请选择" v-model="formInfo.birthday" />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="学历">
                <BaseInput disabled placeholder="请选择" v-model="formInfo.firstEducation" />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="专业">
                <BaseInput disabled placeholder="请选择" v-model="formInfo.specialitieMax" />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="职称" prop="jobTitleId">
                <a-select :disabled="disabled" placeholder="请选择" v-model="formInfo.jobTitleId">
                  <a-spin v-if="fetchingTitle" slot="notFoundContent" size="small" />
                  <a-select-option :disabled="!i.enabled" v-for="i in titleList" :key="i.id" :value="i.id">
                    {{ i.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="本项工作从事开始时间" prop="startTime">
                <a-date-picker
                  :disabled-date="disabledDate"
                  :disabled="disabled" value-format="YYYY-MM-DD" placeholder="请选择"
                  v-model="formInfo.startTime"
                />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="是否专职设备管理员" prop="fullDevice">
                <BSelect :disabled="disabled" v-model="formInfo.fullDevice"
                         :list="[
                           {id:0,name:'否'},
                           {id:1,name:'是'},
                         ]"
                />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="是否为安全讲师" prop="safetyInstructor">
                <a-select :disabled="disabled" placeholder="请选择" v-model="formInfo.safetyInstructor">
                  <a-select-option :value="1">是</a-select-option>
                  <a-select-option :value="0">否</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="是否为安全专家" prop="safetyExpert">
                <a-select :disabled="disabled" placeholder="请选择" v-model="formInfo.safetyExpert">
                  <a-select-option :value="1">是</a-select-option>
                  <a-select-option :value="0">否</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col span="8" v-if="formInfo.safetyExpert == 1 ">
              <a-form-model-item label="分类  " prop="safetyExpertTypeId">
                <a-select :disabled="disabled" placeholder="请选择" v-model="formInfo.safetyExpertTypeId">
                  <a-spin v-if="fetchingSafetyExpert" slot="notFoundContent" size="small" />
                  <a-select-option :disabled="!i.enabled" v-for="i in safetyExpertTypeIdList" :key="i.id" :value="i.id">
                    {{ i.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col span="24">
              <a-form-model-item :disabled="disabled" label="项目经历" prop="projectExperience">
                <b-textarea placeholder="请输入" v-model="formInfo.projectExperience" :disabled="disabled" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>

      <a-card>
        <div>
          <title-name title="人员证书" />
          <div class="mb20" v-if="!disabled">
            <a-button icon="plus" type="primary" @click="editCertificate('add')">新增人员证书</a-button>
            <a-button
              type="danger"
              icon="delete"
              :disabled="rowSelection.selectedRowKeys.length < 1"
              @click="editCertificate('del')"
              class="ml20"
            >批量删除
            </a-button>
          </div>
          <s-table
            :bordered="true"
            ref="table"
            size="default"
            :columns="columns"
            :data="loadData"
            :rowKey="(row) => row.id"
            :row-selection="rowSelection"
            show-size-changer
            show-quick-jumper
            :showPagination="false"
          >
            <template slot="index" slot-scope="text, record, index">{{ index + 1 }}</template>
            <template slot="fileInfoList" slot-scope="text, record">
              <span v-for="(i, index) in record.fileInfoList" :key="i.id">
                  <span v-if="index>0">、</span>
                  <a :href="'/api/ycloud-file-center/oper/download?access_token=' + token +'&fileId=' +i.fileId ">
                    {{ i.fileName }}
                  </a>
                  <a>
                    <a-icon style="cursor: pointer; margin-left: 6px" type="eye" @click="$filePreview(i)" />
                  </a>
              </span>
            </template>
            <template v-if="pageType !== 'look'" slot="operator" slot-scope="text, record,index">
              <a class="base-btn" @click="editCertificate('edit', record,index)">编辑</a>
            </template>
          </s-table>
        </div>

        <div v-if="formInfo.safetyInstructor === 1">
          <title-name title="授课记录" class="mt20" />
          <div class="mb20" v-if="!disabled">
            <a-button icon="plus" type="primary" @click="editRecords('add')">新增授课记录</a-button>
            <a-button
              type="danger"
              :disabled="rowSelection1.selectedRowKeys.length < 1"
              @click="editRecords('del')"
              class="ml20"
              icon="delete"
            >批量删除
            </a-button>
          </div>
          <s-table
            ref="records"
            :bordered="true"
            :columns="columns1"
            :row-selection="rowSelection1"
            :rowKey="(row) => row.id"
            :data="loadData1"
            show-size-changer
            show-quick-jumper
            :showPagination="false"
          >
            <template slot="index" slot-scope="text, record, index">{{ index + 1 }}</template>
            <template slot="fileInfoList" slot-scope="text, record">
              <span v-for="(i, index) in record.fileInfoList" :key="i.id">
                  <span v-if="index>0">、</span>
                  <a :href="'/api/ycloud-file-center/oper/download?access_token=' +token +'&fileId=' +i.fileId ">
                    {{ i.fileName }}
                  </a>
                  <a><a-icon style="cursor: pointer; margin-left: 6px" type="eye" @click="$filePreview(i)" /></a>
              </span>
            </template>
            <template v-if="pageType !== 'look'" slot="operator" slot-scope="text, record,index">
              <a class="base-btn" @click="editRecords('edit', record,index)">编辑</a>
            </template>
          </s-table>
        </div>
      </a-card>

      <div class="tool-btns page-btn-right-top" v-if="!disabled">
        <a-button
          v-if="id !== '' && formInfo.auditStatus === 'DRAFT'"
          type="danger"
          :loading="loading.DELETE"
          @click="handleSave('DELETE')"
        >删除草稿
        </a-button>
        <a-button type="primary" :loading="loading.DRAFT" @click="handleSave('DRAFT')">保存草稿</a-button>
        <a-button type="primary" :loading="loading.SUBMITTED" @click="handleSave('SUBMITTED')">提交
        </a-button>
        <a-button type="primary" @click="$close">关闭</a-button>
      </div>
      <div class="tool-btns page-btn-right-top" v-else>
        <a-button type="primary" @click="$close">关闭</a-button>
      </div>
    </div>
    <update-personnel-certificate
      :visible.sync="visible.certificate"
      :init-data="childInitCertificateData"
      @confirm="okCertificate"
    />
    <update-teaching-records
      :visible.sync="visible.records"
      :init-data="childInitRecordsData"
      @confirm="okRecords"
    />
  </base-breadcrumb>
</template>

<script>
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import { getSelectListByType } from '@/api/safetySupervision/common'
import updatePersonnelCertificate from './updatePersonnelCertificate'
import updateTeachingRecords from './updateTeachingRecords'
import { employees } from '@/api/quality/safe' // api
import { getCurrentUserBranchCom2, getInfoByStaffId } from '@/api/commons'
import api from '@/api/safetySupervision/base/postInfo'
import Vue from 'vue'
import {
  deleteSecurityPersonnel,
  addSecurityPersonnel,
  updateSecurityPersonnel,
  getSecurityPersonnelDraft,
  getOrganizationDetails, findDeptByEmployeeId
} from '@/api/safetySupervision/securityPersonnel'
import SelectPerson from '@/components/Select/SelectPerson'
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
import moment from 'moment'

export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubCompany,
    SelectProject,
    token: '',
    updatePersonnelCertificate,
    updateTeachingRecords,
    ASelectOrgPeople
  },
  data() {
    return {
      getSelectListByType: async e => {
        const [err, res] = await getSelectListByType(e)
        if (!err) {
          return { code: 200, data: res.data.filter(v => v.enabled) }
        }
      },
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '证书类型',
          dataIndex: 'certificateTypeName'
        },
        {
          title: '证书编号',
          dataIndex: 'certificateNo'
        },
        {
          title: '发证日期',
          dataIndex: 'issueDate'
        },
        {
          title: '有效期至',
          dataIndex: 'validityDate'
        },
        {
          title: '备注',
          dataIndex: 'remarks'
        },
        {
          title: '附件',
          dataIndex: 'fileInfoList',
          scopedSlots: { customRender: 'fileInfoList' }
        },
        {
          title: ' 操作',
          dataIndex: 'operator',
          scopedSlots: { customRender: 'operator' }
        }
      ],
      columns1: [
        {
          title: '序号',
          dataIndex: 'index',
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '课题名称',
          dataIndex: 'name'
        },
        {
          title: '课件时长（小时）',
          dataIndex: 'duration'
        },
        {
          title: '授众',
          dataIndex: 'audience'
        },
        {
          title: '授课时间',
          dataIndex: 'teachingTime'
        },
        {
          title: '备注',
          dataIndex: 'remarks'
        },
        {
          title: '附件',
          dataIndex: 'fileInfoList',
          scopedSlots: { customRender: 'fileInfoList' }
        },
        {
          title: ' 操作',
          dataIndex: 'operator',
          scopedSlots: { customRender: 'operator' }
        }
      ],
      // 表格复选框配置
      rowSelection: {
        selectedRowKeys: [],
        onChange(selectedRowKeys, selectedRows) {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      },
      rowSelection1: {
        selectedRowKeys: [],
        onChange(selectedRowKeys, selectedRows) {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      },
      loading: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        NEXT: false
      },
      spinning: false,
      fetchingTitle: false,
      fetchingSafetyExpert: false,
      orgList: [],
      visible: {
        certificate: false,
        records: false
      },
      step: 0,
      childInitCertificateData: {},
      childInitRecordsData: {},
      id: '',
      personnelId: '',
      formInfo: {
        certificates: [],
        teachingRecords: [],
        orgId: '',
        id: null,
        name: '',
        userId: null,
        branchComId: '',
        projectDeptId: '',
        projectId: '',
        safeDeptType: this.$currentPost().code
      },
      titleList: [], //职称列表
      postList:[], //岗位列表
      safetyExpertTypeIdList: [], //安全专家分类列表
      rules: {
        branchComId: [{ required: true, message: '请选择' }],
        projectId: [{ required: true, message: '请选择' }],
        userId: [{ required: true, message: '请选择' }],
        contractTypeId: [{ required: true, message: '请选择' }],
        fullDevice: [{ required: true, message: '请选择' }],
        jobTitleId: [{ required: true, message: '请选择' }],
        projectExperience: [{ required: true, message: '请输入' }],
        safetyExpert: [{ required: true, message: '请选择' }],
        safetyExpertTypeId: [{ required: true, message: '请选择' }],
        safetyInstructor: [{ required: true, message: '请选择' }],
        startTime: [{ required: true, message: '请选择' }],
        beGoodAtMajor: [{ required: true, message: '请输入' }],
        education: [{ required: true, message: '请输入' }],
        safetyPostId: [{ required: true, message: '请选择' }],
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.formInfo.certificates
          })
        })
      },
      loadData1: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.formInfo.teachingRecords
          })
        })
      },
      editIndex: -1,
      isInit: false//标记是否初始化，因为projectId有值的话，会默认触发一次selectChange事件，会导致人员列表重置
    }
  },
  computed: {
    pageType() {
      return this.$route.query.pageType || 'look'
    },
    isDisabled() {
      return this.pageType == 'edit'
    },
    disabled() {
      return this.$route.query.pageType === 'look'
    },
    // 非安全人员api
    apiEdit() {
      console.log(employees)
      return employees
    }
  },
  //傻逼需求，新增的时候，不可以更改分公司和项目
  //编辑的时候，可以更改分公司和项目
  watch: {
    // 'formInfo.projectDeptId'(newVal) {
    //   if (!this.formInfo.id) return
    //   if (newVal) {
    //     this.formInfo.orgId = newVal
    //     this.formInfo.userId = ''
    //   } else {
    //     if (this.formInfo.branchComId) {
    //       this.formInfo.orgId = this.formInfo.branchComId
    //       this.formInfo.userId = ''
    //     } else {
    //       this.formInfo.orgId = ''
    //       this.formInfo.userId = ''
    //     }
    //   }
    //   console.log(' this.formInfo.orgId ,', this.formInfo.orgId )
    //   console.log(' this.formInfo.userId ,', this.formInfo.userId )
    // },
    // 'formInfo.projectId'(newVal) {
    //   console.log('formInfo.projectId',newVal)
    //   if (!this.formInfo.id) return
    //   if (!newVal) {
    //     this.formInfo.projectDeptId = ''
    //     this.formInfo.orgId = this.formInfo.branchComId
    //     this.formInfo.userId = ''
    //   }
    // },
    // 'formInfo.branchComId'(newVal) {
    //   if (!this.formInfo.id) return
    //   if (newVal && !(this.formInfo.projectDeptId)) {
    //     this.formInfo.orgId = newVal
    //     this.formInfo.userId = ''
    //   } else {
    //     this.formInfo.orgId = ''
    //     this.formInfo.userId = ''
    //   }
    // }
  },
  mounted() {
    this.token = Vue.getAcloudProvider().getAccessToken()
    this.id = this.$route.query.id
    // this.$route.meta.title = this.id == '' ? '安全人员新增' : '安全人员编辑'

    this.getSelectList('24')
    this.getSelectList('22')
    this.getPostInfoList();
    let tagat = true
    this.columns.forEach((i) => {
      if (i.dataIndex === 'operator') {
        tagat = false
      }
    })
    if (this.$route.query.id) {
      this.formInfo.id = this.$route.query.id
      this.getDetail()
    } else {
      if (this.formInfo.safeDeptType === 'CO') {
        this.formInfo.orgId = this.$currentPost().orgId
        this.formInfo.branchComId = this.$currentPost().orgId
        this.formInfo.branchComName = this.$currentPost().orgId
        this.formInfo.projectId = ''
        this.formInfo.projectName = ''
      }
      if (this.formInfo.safeDeptType === 'BC') {
        this.formInfo.orgId = this.$currentPost().orgId
        this.formInfo.projectId = ''
        this.formInfo.projectName = ''
      }
      if (this.formInfo.safeDeptType === 'PD') {
        this.formInfo.projectId = this.$currentPost().projectId
        this.formInfo.orgId = this.$currentPost().id
        this.formInfo.branchComId = this.$currentPost().orgId
      }
    }
    if (this.disabled) {
      // this.$route.meta.title = '安全人员查看'
      this.step = 1
      if (!tagat) {
        this.columns.length = this.columns.length - 1
        this.columns1.length = this.columns1.length - 1
      }
    } else {
      if (tagat) {
        this.columns.push({ title: ' 操作', dataIndex: 'operator', scopedSlots: { customRender: 'operator' } })
        this.columns1.push({ title: ' 操作', dataIndex: 'operator', scopedSlots: { customRender: 'operator' } })
      }
    }
  },
  methods: {
    selecOrg(val) {
      if(val.length) {
        this.formInfo.branchComId = val[val.length - 2].orgId
        this.formInfo.orgId = this.formInfo.branchComId
      }
    },
    getProjectInfo(info) {
      this.formInfo.projectDeptId = info.projectDeptOrgId
    },
    handlePost(e){
      let postName = this.postList.find((item)=>item.id===e).post;
      this.formInfo.post = postName;
    },
    onSelectChange(e) {
      if (!this.isInit) return this.isInit = true
      this.formInfo.projectDeptId = e.projectDeptId
    },
   async getPostInfoList(){
      let data = await api.getPostList({status: 1});
      this.postList = data.data || [];

    } ,
    async getDetail() {
      const params = { id: this.formInfo.id }
      this.spinning = true
      const [err, res] = await getSecurityPersonnelDraft(params)
      if (!err) {
        this.formInfo = {
          ...this.formInfo,
          ...res.data
        }

      }
      // console.log('----------', this.formInfo.projectId)
      await this.getOrgEmployeeByUser(this.formInfo.userId)
      if (!this.formInfo.projectId) {
        this.isInit = true
      }
      // console.log('----------', this.formInfo.projectId)
      // await this.getOrganizationDetails()
      this.spinning = false
      this.$refs.table?.refresh(true)
      this.$refs.records?.refresh(true)
    },

    async getOrgEmployeeByUser(id) {
      try {
        const employee = await getInfoByStaffId(id)
        if (employee.data) {
          delete employee.data.id
          delete employee.data.userId
          delete employee.data.postPNames
          this.formInfo.postPNames = []

          this.formInfo.postPNames = employee.data.posts.filter(v => {
            return employee.data.levels.find(w => w.id === v.orgParentId)
          }).map(v => {
            return v.name
          })

          this.formInfo = {
            ...this.formInfo,
            ...employee.data
          }
          this.formInfo.userId = id
          if (this.formInfo.sex == 1) {
            this.formInfo.sex = '男'
          }
          if (this.formInfo.sex == 0) {
            this.formInfo.sex = '女'
          }
        }
        // console.log('get2', this.formInfo)
      } catch (err) {
        console.error(err)
      }
    },

    async requestBranchCom() {
      let res = await getCurrentUserBranchCom2({ tagCodes: ['BC'] })
      if (res.data) {
        res.data.map(v => {
          v.id = v.orgId
          v.name = v.orgName
        })
        if (this.formInfo.safeDeptType === 'CO') {
          return { code: 200, data: [{ id: this.$currentPost().orgId, name: '总部机关安监部' }, ...res.data] }
        }
        return { code: 200, data: res.data }
      }
      return { code: 200, data: [] }
    },
    disabledDate(current) {
      return current && current > moment().endOf('day')
    },
    async getSelectList(type) {
      this.fetchingTitle = true
      this.fetchingSafetyExpert = true
      const [err, res] = await getSelectListByType({ type })
      if (!err) {
        this.fetchingTitle = false
        this.fetchingSafetyExpert = false
        if (type == 22) {
          this.safetyExpertTypeIdList = res.data || []
        } else if (type == 24) {
          this.titleList = res.data || []
        }
      }
    },

    // 处理更新操作（新增、编辑）
    editCertificate(type, data = { id: Date.now() }, editIndex = -1) {
      this.editIndex = editIndex
      if (type === 'del') {
        this.$confirm({
          title: '温馨提示',
          content: '确定是否删除数据？',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => {
            return this.deleteCertificate(this.rowSelection.selectedRowKeys)
          }
        })
      } else {
        this.childInitCertificateData = {
          ...data,
          pageType: type
        }
        this.visible.certificate = true
      }
    },
    okCertificate(e) {
      if (this.editIndex !== -1) {
        this.formInfo.certificates[this.editIndex] = e
      } else {
        this.formInfo.certificates.push(e)
      }
    },
    deleteCertificate(data) {
      data.map(v => {
        let res = this.formInfo.certificates.findIndex(w => w.id === v)
        if (res !== -1) {
          this.formInfo.certificates.splice(res, 1)
        }
      })
      this.$message.success('删除成功')
      this.rowSelection.selectedRowKeys = []
    },
    okRecords(e) {
      if (this.editIndex !== -1) {
        this.formInfo.teachingRecords[this.editIndex] = e
      } else {
        this.formInfo.teachingRecords.push(e)
      }
    },
    async deleteRecords(data) {
      data.map(v => {
        let res = this.formInfo.teachingRecords.findIndex(w => w.id === v)
        if (res !== -1) {
          this.formInfo.teachingRecords.splice(res, 1)
        }
      })
      this.$message.success('删除成功')
      this.rowSelection1.selectedRowKeys = []
    },
    editRecords(type, data = { id: Date.now() }, editIndex = -1) {
      this.editIndex = editIndex
      if (type === 'del') {
        this.$confirm({
          title: '温馨提示',
          content: '确定是否删除数据？',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => {
            return this.deleteRecords(this.rowSelection1.selectedRowKeys)
          }
        })
      } else {
        this.childInitRecordsData = {
          ...data,
          pageType: type
        }
        this.visible.records = true
      }
    },

    async getPeople(e) {
      console.log('get1', this.formInfo)
      // console.log('getPle',e)
      this.spinning = true
      await this.getOrgEmployeeByUser(e.id)
      this.spinning = false
    },
    async getOrganizationDetails() {
      const params = {
        id: this.formInfo.orgId
      }
      const [err, res] = await findDeptByEmployeeId(params)
      if (!err) {
        this.orgList = res.data
        if (this.orgList.length > 0) {
          this.formInfo.branchComId = this.orgList[0].id
          this.formInfo.branchComName = this.orgList[0].name
        }
        if (this.orgList.length === 2) {
          this.formInfo.projectId = this.orgList[1].id
          this.formInfo.projectName = this.orgList[1].name
        }
      }
    },

    validateForm() {
      let flag = false
      this.$refs.form.validate((valid) => {
        flag = valid
      })
      if (!flag) {
        this.$noticeWarning('请填写完整')
      }
      return flag
    },
    async deleteDraft() {
    },
    // 处理增、删、改操作
    async handleSave(status) {
      if (status !== 'DELETE' && !this.validateForm()) return
      if (this.loading[status]) return
      this.loading[status] = true
      const params = {
        ...this.formInfo,
        auditStatus: status
      }
      const { pageType } = this.$route.query
      const fn = pageType === 'edit' ? updateSecurityPersonnel : addSecurityPersonnel
      const map = {
        DELETE: deleteSecurityPersonnel,
        DRAFT: fn,
        SUBMITTED: fn
      }
      if (status === 'DELETE') {
        let that = this
        this.$confirm({
          title: '温馨提示',
          content: '确定是否删除数据？',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => {
            return that.deleteSecurityPersonnel(params)
          }
        })
      } else {
        //certificates: [], teachingRecords: []
        if (!params.id) {
          params.certificates.map(v => {
            delete v.id
          })
          params.teachingRecords.map(v => {
            delete v.id
          })
        }
        const [err, res] = await map[status](params)
        this.loading[status] = false
        if (!err) {
          this.formInfo.id = res.data.id
          this.getDetail()
          this.$message.success('成功')
          this.$close()
        }
      }
    },
    async deleteSecurityPersonnel(params) {
      const [err, res] = await deleteSecurityPersonnel(params)
      if (!err) {
        this.$message.success('删除成功')
        this.handleClose()
      }
    }
  }
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.flex {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  height: 40px;
}

.tool-btns {
  display: flex;
  justify-content: flex-end;

  .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}
.history-data{
   .post{
       border: 1px solid #d9d9d9;
      line-height: 32px;
      height: 32px;
      background-color: #F5F5F5;
      cursor: not-allowed;
      border-radius: 3px;
      padding-left: 10px;
   }

}
</style>
